#coding=utf-8
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth.models import User
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import json,random,xlwt,time,os,MySQLdb
from metal.settings import MEDIA_ROOT
from models import Metal,DisposeProgram,NewsLink,Image,MyUserModel
from django.db import connection
import sys,simplejson,csv

reload(sys)
sys.setdefaultencoding('utf8')

def login(request):
    return render_to_response('login.html',context_instance=RequestContext(request))

#登陆界面校验
@csrf_exempt
def loginValidate(request):
    name=request.POST.get('username')
    password=request.POST.get('password')
    if not name or not password:
        info='用户名或者密码为空'
        return render_to_response('login.html',{'error':info},context_instance=RequestContext(request))
    try:
        user=MyUserModel.objects.get(username=name,password=password)
        if user is not None:
          return HttpResponseRedirect('/')
    except:
        info='用户名或者密码错误'
        return render_to_response('login.html',{'error':info},context_instance=RequestContext(request))

#分页
def p_page():
    return 10
#主界面的信息展示
def homepage(request):
    # user=request.session.get('user')
    # if user:
    per_page=p_page()
    metal_list = Metal.objects.all()
    kind_list = ['all','Pb','Hg','Cr','As','Mn','Zn','Cd','others']
    value_list=['全部','铅','汞','铬','砷','锰','锌','镉','其他']
    list_industry=['化工','金属矿采选业','金属冶炼及压延加工业','金属制品业','铅蓄电池','电力','制灯','废物处置','其它']
    list_kind_industry=['chemical_industry','metal_industry','smelt_industry','metalwork_industry','battery_industry','power_industry','lamp_industry','waste_industry','others']
    for i in range(len(metal_list)):
        metal=metal_list[i]
        if metal.metal_kind:
            i=kind_list.index(metal.metal_kind)
            type=value_list[i]
            metal.metal_kind=type
        if metal.occupation_standard:
            id=list_kind_industry.index(metal.occupation_standard)
            metal.occupation_standard= list_industry[id]

    paginator = Paginator(metal_list,per_page)
    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        contacts = paginator.page(1)
    except EmptyPage:
        contacts = paginator.page(paginator.num_pages)
    _pageData = []
    for i in xrange(len(contacts.object_list)):
        _item = contacts.object_list[i]
        _tmpObj = {}
        _tmpObj['id'] = _item.id
        _tmpObj['accident'] = _item.accident
        _tmpObj['metal_kind']= _item.metal_kind
        _tmpObj['time'] = _item.time
        _tmpObj['accident_place'] = _item.accident_place
        _tmpObj['longitude'] = _item.longitude
        _tmpObj['latitude'] = _item.latitude
        _tmpObj['occupation_standard'] = _item.occupation_standard
        _tmpObj['accident_description'] = _item.accident_description
        _tmpObj['viticm_kind'] = _item.viticm_kind
        _tmpObj['viticm_kind_name'] = _item.viticm_kind_name
        _tmpObj['viticm_kind_count'] = _item.viticm_kind_count        
        _pageData.append(_tmpObj)
    _pageData = simplejson.dumps(_pageData)
    return render_to_response('index.html',{'paginator':paginator,'contacts':contacts,'pageData':_pageData},context_instance=RequestContext(request))


#t添加按钮
def MetalAdd(request):
    kind_list = ['Pb','Hg','Cr','As','Mn','Zn','Cd','Others']
    value_list=['铅','汞','铬','砷','锰','锌','镉','其他']
    metal_list = []
    size = len(kind_list)
    for i in range(size):
        kind = kind_list[i]
        value = value_list[i]
        metal = {}
        metal['kind'] = kind
        metal['value'] = value
        metal_list.append(metal)
    industry_list=[]
    list_industry=['化工','金属矿采选业','金属冶炼及压延加工业','金属制品业','铅蓄电池','电力','制灯','废物处置','其它']
    list_kind_industry=['chemical_industry','metal_industry','smelt_industry','metalwork_industry','battery_industry','power_industry','lamp_industry','waste_industry','Others']
    for i in range(len(list_industry)):
        ind_value=list_industry[i]
        ind_kind=list_kind_industry[i]
        industry ={}
        industry['kind']=ind_kind
        industry['value']=ind_value
        industry_list.append(industry)

    return render_to_response('data-manage.html',{'metal_list':metal_list,'industry_list':industry_list},context_instance=RequestContext(request))

#添加信息
@csrf_exempt
def add_btn_submit(request):
    accident = request.POST.get('name')
    metal_kind = request.POST.get('metal_type')
    if metal_kind == '其他':
        metal_kind+=','+request.POST.get('metal_kind')
    kind_list = ['Pb','Hg','Cr','As','Mn','Zn','Cd','Others']
    value_list=['铅','汞','铬','砷','锰','锌','镉','其他']
    id=kind_list.index(metal_kind)
    metal_kind_en=value_list[id]
    time = request.POST.get('time')
    accident_palce_pro = request.POST.get('cmbProvince')
    accident_palce_city = request.POST.get('cmbCity')
    accident_palce_are = request.POST.get('cmbArea')
    accident_place=accident_palce_pro+'|'+accident_palce_city+'|'+accident_palce_are
    longitude = request.POST.get('longitude')
    latitude =  request.POST.get('latitude')
    list_industry=['化工','金属矿采选业','金属冶炼及压延加工业','金属制品业','铅蓄电池','电力','制灯','废物处置','其它']
    list_kind_industry=['chemical_industry','metal_industry','smelt_industry','metalwork_industry','battery_industry','power_industry','lamp_industry','waste_industry','Others']
    occupation_standard  =  request.POST.get('occupation_standard')
    ids=list_kind_industry.index(occupation_standard)
    occupation_standard_en=list_industry[ids]
    # occupation_standard=request.POST.get('occupation_standard_auto')
    viticm_kind = request.POST.get('viticm_kind')
    viticm_kind_name =  request.POST.get('viticm_kind_name')
    viticm_kind_count =  request.POST.get('viticm_kind_count')
    accident_description = request.POST.get('accident_description')
    metal=Metal.objects.create(accident=accident,metal_kind=metal_kind,time=time,accident_place=accident_place,
                               longitude=longitude,latitude=latitude,occupation_standard=occupation_standard,
                               viticm_kind=viticm_kind,viticm_kind_name=viticm_kind_name,viticm_kind_count=viticm_kind_count,
                               accident_description=accident_description,metal_kind_en=metal_kind_en,occupation_standard_en=occupation_standard_en)
    pollution_measure=request.POST.get('pollution_measure')
    environment_measure=request.POST.get('environment_measure')
    crowd_measure=request.POST.get('crowd_measure')
    information_measure=request.POST.get('information_measure')
    after_measure=request.POST.get('after_measure')
    law_measure=request.POST.get('law_measure')
    measure=DisposeProgram.objects.create(metal=metal,pollution_measure=pollution_measure,crowd_measure=crowd_measure,
                                          information_measure=information_measure,after_measure=after_measure,law_measure=law_measure)
    news=request.POST.getlist('news_link')
    for news_url in news:
      new=NewsLink.objects.create(metal=metal,news_link=news_url)
    images = request.FILES.getlist('image','')
    imagenames=request.POST.getlist('imagename')
    for i in range(len(images)):
        image=images[i]
        imagename=imagenames[i]
        imagemodel=Image.objects.create(metal=metal,image=image,imagename=imagename)
    return HttpResponseRedirect('/')

#筛选信息
def filter_metal(request,param):
    if param == 'all':
        metal_list=Metal.objects.all()
    else:
        metal_list=Metal.objects.filter(metal_kind=param)
    _pageData = []
    kind_list = ['Pb','Hg','Cr','As','Mn','Zn','Cd','Others']
    value_list=['铅','汞','铬','砷','锰','锌','镉','其他']
    list_industry=['化工','金属矿采选业','金属冶炼及压延加工业','金属制品业','铅蓄电池','电力','制灯','废物处置','其它']
    list_kind_industry=['chemical_industry','metal_industry','smelt_industry','metalwork_industry','battery_industry','power_industry','lamp_industry','waste_industry','Others']
    for i in xrange(len(metal_list)):
        _item = metal_list[i]
        _tmpObj = {}
        _tmpObj['id'] = _item.id
        _tmpObj['accident'] = _item.accident
        _tmpObj['metal_kind']= _item.metal_kind
        _tmpObj['metal_kind_en']= _item.metal_kind_en
        _tmpObj['time'] = _item.time
        _tmpObj['accident_place'] = _item.accident_place
        _tmpObj['longitude'] = _item.longitude
        _tmpObj['latitude'] = _item.latitude
        _tmpObj['occupation_standard'] = _item.occupation_standard
        _tmpObj['occupation_standard_en'] =_item.occupation_standard_en
        _tmpObj['accident_description'] = _item.accident_description
        _tmpObj['viticm_kind'] = _item.viticm_kind
        _tmpObj['viticm_kind_name'] = _item.viticm_kind_name
        _tmpObj['viticm_kind_count'] = _item.viticm_kind_count        
        _pageData.append(_tmpObj)
    _pageData = simplejson.dumps(_pageData)
    return HttpResponse(_pageData)
#统计
def metal_statistics(request):
    return render_to_response('statistics.html',context_instance=RequestContext(request))
#删除信息
@csrf_exempt
def delete_metal(request,param):
    metal=Metal.objects.get(id=param)
    images=Image.objects.filter(metal=metal)
    for image in images:
        if image:
            os.remove(MEDIA_ROOT+image.image.name)
    metal.delete()
    return HttpResponseRedirect('/')

#修改信息z主界面的按钮
def metal_modify(request,param):
    selected_metal=Metal.objects.get(id=param)
    measure=DisposeProgram.objects.get(metal=selected_metal)
    news=NewsLink.objects.filter(metal=selected_metal)
    images=Image.objects.filter(metal=selected_metal)
    kind_list = ['all','Pb','Hg','Cr','As','Mn','Zn','Cd','others']
    value_list=['全部','铅','汞','铬','砷','锰','锌','镉','其他']
    metal_list = []
    size = len(kind_list)
    for i in range(size):
        kind = kind_list[i]
        value = value_list[i]
        metal = {}
        metal['kind'] = kind
        metal['value'] = value
        metal_list.append(metal)
    region_names = selected_metal.accident_place.split('|')
    prov_name = None
    city_name = None
    area_name = None
    if region_names and len(region_names) == 3:
        prov_name = region_names[0]
        city_name = region_names[1]
        area_name = region_names[2]
    industry_list=[]
    list_industry=['化工','金属矿采选业','金属冶炼及压延加工业','金属制品业','铅蓄电池','电力','制灯','废物处置','其它']
    list_kind_industry=['chemical_industry','metal_industry','smelt_industry','metalwork_industry','battery_industry','power_industry','lamp_industry','waste_industry','others']
    for i in range(len(list_industry)):
        ind_value=list_industry[i]
        ind_kind=list_kind_industry[i]
        industry ={}
        industry['kind']=ind_kind
        industry['value']=ind_value
        industry_list.append(industry)
    viticm_kind=selected_metal.viticm_kind
    viticm_kind_name=selected_metal.viticm_kind_name
    context_dict = {'metal':selected_metal,'measure':measure,'metal_list':metal_list,'industry_list':industry_list,'images':images,'news':news}
    context_dict['prov_name'] = prov_name
    context_dict['city_name'] = city_name
    context_dict['area_name'] = area_name
    context_dict['viticm_kind']=viticm_kind
    context_dict['viticm_kind_name']=viticm_kind_name
    return render_to_response('data-manage.html',context_dict,context_instance=RequestContext(request))

#修改信息提交按钮
@csrf_exempt
def metal_update_btn(request):
    param = request.POST.get('id')
    accident = request.POST.get('name')
    metal_kind = request.POST.get('metal_type')
    if metal_kind=='其他':
       metal_kind=request.POST.get('metal_kind')
    time = request.POST.get('time')
    accident_palce_pro = request.POST.get('cmbProvince')
    accident_palce_city = request.POST.get('cmbCity')
    accident_palce_are = request.POST.get('cmbArea')
    accident_palce=accident_palce_pro+'|'+accident_palce_city+'|'+accident_palce_are
    longitude = request.POST.get('longitude')
    latitude =  request.POST.get('latitude')
    occupation_standard  =  request.POST.get('occupation_standard')
    if occupation_standard=='其他':
        occupation_standard=request.POST.get('occupation_standard_auto')
    viticm_kind = request.POST.get('viticm_kind')
    viticm_kind_name =  request.POST.get('viticm_kind_name')
    viticm_kind_count =  request.POST.get('viticm_kind_count')
    accident_description = request.POST.get('accident_description')
    metal=Metal.objects.get(id=param)
    metal.accident=accident
    metal.metal_kind=metal_kind
    metal.time=time
    metal.accident_palce=accident_palce
    metal.longitude=longitude
    metal.latitude=latitude
    metal.occupation_standard=occupation_standard
    metal.viticm_kind=viticm_kind
    metal.viticm_kind_name=viticm_kind_name
    metal.viticm_kind_count=viticm_kind_count
    measure=DisposeProgram.objects.get(metal=metal)
    pollution_measure=request.POST.get('pollution_measure')
    environment_measure=request.POST.get('environment_measure')
    crowd_measure=request.POST.get('crowd_measure')
    information_measure=request.POST.get('information_measure')
    after_measure=request.POST.get('after_measure')
    law_measure=request.POST.get('law_measure')
    measure.pollution_measure=pollution_measure
    measure.environment_measure=environment_measure
    measure.crowd_measure=crowd_measure
    measure.information_measure=information_measure
    measure.after_measure=after_measure
    measure.law_measure=law_measure
    measure.save()
    image_dao=Image.objects.filter(metal=metal)
    oldimages=request.POST.getlist('oldImage')
    images = request.FILES.getlist('image','')
    imagenames=request.POST.getlist('imagename')
    for image in image_dao:
        if image.image not in oldimages:
            os.remove(MEDIA_ROOT+image.image.name)
            image.delete()
    for image in images:
        i=images.index(image)
        Image.objects.create(metal=metal,image=image,imagename=imagenames[i])
    new_dao=NewsLink.objects.filter(metal=metal)
    news=request.POST.getlist('news_link')
    for new in new_dao:
        new.delete()
    for  new_url in news:
        NewsLink.objects.create(metal=metal,news_link=new_url)
    metal.save()
    return HttpResponseRedirect('/')


#查看详情
def metal_detail(request,param):
    metal=Metal.objects.get(id=param)
    kind_list = ['all','Pb','Hg','Cr','As','Mn','Zn','Cd','others']
    value_list=['全部','铅','汞','铬','砷','锰','锌','镉','其他']
    list_industry=['化工','金属矿采选业','金属冶炼及压延加工业','金属制品业','铅蓄电池','电力','制灯','废物处置','其它']
    list_kind_industry=['chemical_industry','metal_industry','smelt_industry','metalwork_industry','battery_industry','power_industry','lamp_industry','waste_industry','others']
    i=kind_list.index(metal.metal_kind)
    type=value_list[i]
    metal.metal_kind=type
    id=list_kind_industry.index(metal.occupation_standard)
    metal.occupation_standard=list_industry[id]
    image=Image.objects.filter(metal=metal)
    news=NewsLink.objects.filter(metal=metal)
    return render_to_response('data-detail.html',{'metal':metal,'images':image,'news':news},context_instance=RequestContext(request))


#metal信息导出信息
@csrf_exempt
def metal_export(request):
    list=request.POST.getlist('list')
    metal_list=[]
    for id in list:
        metal=Metal.objects.get(id=id)
        metal_list.append(metal)
    wbk=xlwt.Workbook()
    sheet=wbk.add_sheet(u'重金属污染事故案')
    sheet.write(0,0,u'编号')
    sheet.write(0,1,u'事故名称')
    sheet.write(0,2,u'重金属类型')
    sheet.write(0,3,u'时间')
    sheet.write(0,4,u'事故地点')
    sheet.write(0,5,u'行业类型')
    sheet.write(0,6,u'受体类型')
    sheet.write(0,7,u'受害人数')
    sheet.write(0,8,u'事故后描述')
    row=1
    for metal in metal_list:
        sheet.write(row,0,metal.id)
        sheet.write(row,1,metal.accident)
        sheet.write(row,2,metal.metal_kind)
        sheet.write(row,3,metal.time)
        sheet.write(row,4,metal.accident_place)
        sheet.write(row,5,metal.occupation_standard)
        sheet.write(row,6,metal.viticm_kind_name)
        sheet.write(row,7,metal.viticm_kind_count)
        sheet.write(row,8,metal.accident_description)
        row+=1
    media=os.path.join(os.path.dirname(__file__), 'medias/').replace('\\', '/')
    filename=u'污染场地修复技术列表.xls'
    wbk.save(filename)
    fp = open(filename, 'rb')
    data = fp.read()
    fp.close()
    filename=r'重金属污染事故案列表.xls'
    response = HttpResponse(data,mimetype='application/octet-stream')
    response['Content-Encoding'] = 'utf-8'
    response['Content-Disposition'] = 'attachment; filename=%s' % filename

    return response









# #统计事故
# def Summary(request,param):
#     dict={}
#     try:
#      conn= MySQLdb.connect(host='localhost',user='root',passwd="123456",db='metal')
#     except Exception, e:
#       print  e
#       sys.exit()
#     cursor=conn.cursor()
#     #查询受害总数
#     if param==1:
#         sql='select count(viticm_kind_count) from Metal'
#         cursor.execute(sql)
#         data=cursor.fetchall()
#     #查询不同年份事故数量,各省事故数量、各类型重金属事故数量、受损害人数、不同受体的人数
#     else:
#         sql='select %s，viticm_kind_count from Metal'%param
#         cursor.execute(sql)
#         records=cursor.fetchall()
#         for record in records:
#             param=record.param
#             if param in dict:
#                 dict[param]+=record.viticm_kind_count
#             else:
#                 dict[param]=record.viticm_kind_count
#
# #统计信息的导出



@csrf_exempt
def statistic(request):
    if request.method == 'GET':
        return render_to_response('statistics.html',context_instance=RequestContext(request))
    if request.method == 'POST':
        metalType = request.POST.get('metalType')
        cmbProvince = request.POST.get('cmbProvince')
        age = request.POST.get('age')
        victimKind = request.POST.get('victimKind')
        if not metalType and not cmbProvince and not age and not victimKind:
            return HttpResponse("不能同时为空值")
        try:
            if metalType == '全部' and not cmbProvince and not age and not victimKind:
                metals = Metal.objects.all()
            elif metalType == '全部' and cmbProvince and age and victimKind:
                metals = Metal.objects.filter(metal_kind_en__contains="", accident_place__contains=cmbProvince,time__contains=age, viticm_kind_name__contains=victimKind)
            elif metalType == '全部' and (not cmbProvince or not age or not victimKind):
                metals = Metal.objects.filter(metal_kind_en__contains="", accident_place__contains=cmbProvince,time__contains=age, viticm_kind_name__contains=victimKind)
            else:
                metals = Metal.objects.filter(metal_kind_en__contains=metalType, accident_place__contains=cmbProvince,time__contains=age, viticm_kind_name__contains=victimKind)
            accidentCount = len(metals)
            kindCount = 0
            for metal in metals:
                kindCount += metal.viticm_kind_count
        except Exception,e:
            print e
            return HttpResponse("操作错误")
        if request.POST.has_key("statisticBtn"):
            return render_to_response('statistics.html',{'metals':metals,'accidentCount':accidentCount,'kindCount':kindCount, 'metalType':metalType, 'cmbProvince':cmbProvince, 'age':age, 'victimKind':victimKind})
        elif request.POST.has_key("outPut"):
            filename = 'statisticResult'
            Response = HttpResponse(mimetype='text/csv')
            Response['Content-Disposition'] = 'attachment;filename=%s' % filename + '.csv'
            writer = csv.writer(Response)
            writer.writerow([u'事故总数'.encode('GBK'), u'受损总人数'.encode('GBK')])
            writer.writerow([accidentCount,kindCount])
            return Response
            # filename = r'统计表'
            # response = HttpResponse(mimetype='application/vnd.ms-excel')
            # response['Content-Disposition'] = 'attachment;filename=%s'% filename
            # wb = xlwt.Workbook(encoding = 'utf-8')
            # sheet = wb.add_sheet(u'统计')
            # sheet.write(0,0, '事故总数')
            # sheet.write(0,1, '受损人数')
            # sheet.write(1,0, accidentCount)
            # sheet.write(1,1,kindCount)
            # output = StringIO.StringIO()
            # wb.save(output)
            # output.seek(0)
            # response.write(output.getvalue())
            # return response




